#include"namestorage.h"

using std::string;

NameStorage::NameStorage() {
}

NameStorage::NameStorage(NameStorage const & ns) : storage(ns.storage) {
}

NameStorage::~NameStorage() {
}

string const & NameStorage::operator[](int i) const {
	return storage[i];
}

string & NameStorage::operator[](int i) {
	return storage[i];
}

int NameStorage::findName(string const & s) const {
	bool stop = false;
	unsigned i = 0;
	for(i = 0; !stop && (i < storage.size()); i++)
		stop = (s.compare(storage[i]) == 0);
	return stop ? (i - 1) : -1;
}

unsigned NameStorage::addName(string const & s) {
	int i = findName(s);
	if (i == -1) {
		storage.push_back(s);
		return storage.size() - 1;
	}
	else
		return i;
}

unsigned NameStorage::addOrRename(string const & s) {
	int i = findName(s);
	if (i == -1) {
		storage.push_back(s);
	}
	else {
		string newname = s;
		do {
			newname += "1";
		} while (findName(newname) != -1);
		storage.push_back(newname);
	}
	return (storage.size() - 1);
}

unsigned NameStorage::resolveConflict(std::set<unsigned> const & stoplist, std::string const & suggest) {
	int i = findName(suggest);
	if ((i == -1) || (stoplist . find(i) == stoplist . end()))
		return (i == -1) ? addName(suggest) : i;
	else
		if (stoplist . size() < storage . size() - 1) {
			unsigned found = 0;
			for( unsigned i = 1; (found == 0) && (i < storage . size()); ++i )
				found = (stoplist . find(i) == stoplist . end()) ? i : 0;
			return found;
		}
		else
			return addOrRename(suggest);
}
